<template>
    <Dialog
        title="缓存列表"
        :visible="props.visible"
        confirm-btn-text="重放"
        @cancel="handleCancel"
        @confirm="handleConfirm"
    >
        <LList :items="state.cacheRequests" label="listName" @select="handleSelected"/>
        <template v-slot:footer>
            <LButton @click="handleReply" class="mr-2">
                重放请求
            </LButton>
            <LButton @click="handleCancel" type="default">
                取消
            </LButton>
        </template>
    </Dialog>
</template>
<script setup>
import { Dialog, LList } from "@/components";
import { useChromeStorage } from "@/utils/chrome-storage.js";
import { reactive, watch } from "vue";
import { repaly } from "@/utils/request-util";

const emits = defineEmits(["update:visible"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  onDialogCancel: {
    type: Function,
    default: () => ({}),
  },
  onDialogConfirm: {
    type: Function,
    default: () => ({}),
  },
});

const chromeStorage = useChromeStorage();
const state = reactive({
  cacheRequests: [],
});

watch(() => props.visible, () => {
  chromeStorage.getAll((data) => {
    const temp = [];
    Object.keys(data).forEach(key => {
      data[key].listName = key;
      temp.push(data[key]);
    });
    state.cacheRequests = temp;
  });
});

const handleConfirm = () => {
  this.$emit("confirm");
};

let selected = undefined;
const handleSelected = (item) => {
  selected = item;
}; 
const handleReply = () => {
  repaly(selected);
};
const handleCancel = () => {
  emits("update:visible", false);
};
</script>